import React, {useState, useEffect, useMemo} from 'react';
import { WaitUmd, uReal, save_data, show_mt, is_empty, uDb, cline, Btn, obj_str, loc, PanelFind, Ret, Title, filter_row, useCmd,
    obj_float, get_batch, useHigh, GridTable } from 'sui';
import { reload, load_col_psn } from './cmd';
import { DlgVal } from './ctl';

const PsnView = ({ cur, hreturn, no_acc }) => {
    const [main, setMain] = useState();
    const [col, setCol] = useState();
    const [open_val, openVal] = useState(false);
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        load_col_psn(setCol);
        reload(null, setMain, cur);
    }, [cur]);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const getStandout = useMemo(() => {
        if (is_empty(main)) {
            return 0;
        }

        let tmp = 0;
        let len = 0;

        main.forEach(d => {
            if (!d["standout"]) {
                return;
            }

            const s = parseFloat(d["standout"]);
            if (isNaN(s)) {
                return;
            }

            tmp += s;
            len += 1;
        });

        if (len > 0) {
            tmp = tmp / len;
        }

        return tmp.toFixed(3);
    }, [main]);

    const act = {
        "add": (v) => {
            umd.startWait();
            uDb(null, "psn/add",
                {
                    line: cline(),
                    k: obj_str(cur, "sn"),
                    v: [{sn: obj_str(v, "sn")}]
                },
                r => reload(umd.endWait, setMain, cur),
                e => umd.setErr(), true);
        }
    };

    const pact = {
        "add": v => openVal(true),
        "sync": v => {
            umd.startWait();

            uReal(null, "group/sync",
                {
                    line: cline(),
                    tsn: obj_str(cur, "tech"),
                },
                r => reload(umd.endWait, setMain, cur),
                e => umd.setErr());
        }
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 110));

        return tmp;
    };

    const hout = () => {
        const name = obj_str(cur, "sn");
        const col = getCol();

        save_data(main, col, name, umd);
    };

    const hauto = () => {
        if (is_empty(main)) {
            alert("没有数据");
            return;
        }

        const name = obj_str(cur, "sn");

        const col = [
            {name: "位置", key: 'outpos'},
            {name: "外圈批次", key: 'outbsn'},
            {name: "外圈编号", key: 'sn'},
            {name: "外圆", key: 'outdia'},
            {name: "外圈沟径", key: 'outdt'},
            {name: "外圈宽度", key: 'outwidth'},
            {name: "", key: 'space'},
            {name: "位置", key: 'inpos'},
            {name: "内圈批次", key: 'inbsn'},
            {name: "内圈编号", key: 'insn'},
            {name: "内孔", key: 'india'},
            {name: "内圈沟径", key: 'indt'},
            {name: "内圈宽度", key: 'inwidth'},
            {name: "沟径差", key: 'diff'},
            {name: "球规值", key: 'std'},
            {name: "分规值", key: 'sub'},
            {name: "De-di-2*Dw", key: 'calc'},
            {name: "钢球批次", key: 'bsn'},
            {name: "型号", key: 'tech'},
        ];

        const row = main.map((t, i) => {
            const d = {...t};

            d["calc"] = obj_float(d, "outdia") - obj_float(d, "india") - 2 * (obj_float(d, "dw"));
            d["diff"] = obj_float(d, "outdt") - obj_float(d, "indt");
            d["outpos"] = i + 1;
            d["inpos"] = i + 1;
            d["outbsn"] = get_batch(obj_str(d, "sn"));
            d["inbsn"] = get_batch(obj_str(d, "insn"));

            return d;
        });

        save_data(row, col, name, umd);
    };

    const btnAuto = () => {
        const name = obj_str(cur, "sn");
        if (!name.startsWith("auto")) {
            return null;
        }

        return <Btn className="ml-4" hcmd={hauto}>导出为分选机格式</Btn>;
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn color="green" hcmd={() => umd.pact(pact, null, "sync")} disabled={no_acc("bfb")}>{loc("l_790")}</Btn>
            <Btn className="ml-4" hcmd={() => umd.pact(pact, null, "add")} disabled={no_acc("bfa")}>{loc("l_239")}</Btn>
            <Btn className="ml-4" hcmd={hout}>{loc("l_298")}</Btn>
            {btnAuto()}
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            <Title mod={`${obj_str(cur, "sn")} ( ${obj_str(cur, "tech")} )`} sub={loc("l_152")}>{loc("l_350")}</Title>
            <div className="ml-10 bg-teal-300 px-3 pt-2 pb-1">{loc("l_830")}<span className="ml-6">{getStandout}</span></div>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow}/>
            <DlgVal open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} main={main}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {PsnView};
